<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>getSnapShotBeforeUpdata使用场景</title>
    <style>
      .box {
        border: 1px solid #ccc;
        width: 200px;
        height: 150px;
        overflow: auto;
      }
      .news {
        text-align: center;
        height: 30px;
        line-height: 30px;
        background-color: aqua;
      }
    </style>
  </head>
  <body>
    <div id="test"></div>
    <!-- 引入react核心库  优先 -->
    <script type="text/javascript" src="../js/react.development.js"></script>
    <!-- 引入react-dom用于支持react操作DOM，依赖react核心库 -->
    <script
      type="text/javascript"
      src="../js/react-dom.development.js"
    ></script>
    <!-- 引入babel，用于将jsx转换为js -->
    <script type="text/javascript" src="../js//babel.min.js"></script>
    <script type="text/babel">
      //    这节课学getSnapShotBeforeUpdata()使用场景 ：
      class NewList extends React.Component {
        state = {
          newsArr: [],
        };
        componentDidMount() {
          setInterval(() => {
            const { newsArr } = this.state;
            const news = "新闻" + (newsArr.length + 1);
            this.setState({
              newsArr: [news, ...newsArr],
            });
          }, 1000);
        }
        getSnapshotBeforeUpdate(preProps, preState) {
          return this.refs.list.scrollHeight;
        }
        componentDidUpdate(preProps, preState, snapShotValue) {
          this.refs.list.scrollTop +=
            this.refs.list.scrollHeight - snapShotValue;
        }

        render() {
          return (
            <div className="box" ref="list">
              {this.state.newsArr.map((item, index) => {
                return (
                  <div className="news" key={index}>
                    {item}
                  </div>
                );
              })}
            </div>
          );
        }
      }

      ReactDOM.render(<NewList />, document.getElementById("test"));
    </script>
  </body>
</html>
